var publictool = require("../../publictool/publictool");

var db = require('../../db/db');

exports.register = function (req, res) {
    var requestData = '';
    req.addListener('data', function (postDataChunk) {
        requestData += postDataChunk;
    });

    req.addListener('end', function () {
        publictool.putlog(req, requestData);
        var phone = publictool.checkoutdata(res, requestData);
        if (!phone) {
            return;
        }

        db.checkusernum()
            .then(function (isok) {
                if (isok) {
                    if (phone.account && phone.password && phone.lever && phone.start_timestamp && phone.end_timestamp) {
                        adduser(phone, res);
                    } else {
                        publictool.returnErr(res, '参数错误', 1);
                        return;
                    }
                } else {
                    publictool.returnErr(res, '数据库错误', 1);
                    return;
                }
            });
    });
}

function adduser(phone, res) {
    var client = db.client();

    var sql = 'SELECT * FROM user where account = ?';
    var addSqlParams = [phone.account];

    client.query(sql, addSqlParams, function (err, result) {
        if (err) {
            console.log('[SELECT ERROR] - ', err.message);
            publictool.returnErr(res, '查询参数错误', 1);
            client.end();
            return;
        }

        if (result.length > 0) {
            publictool.returnErr(res, '用户已存在', 1);
            client.end();
            return;
        } else {
            var addSql = 'INSERT INTO user(account,password,lever,start_timestamp,end_timestamp,company_name,name,tel,qq,accesstoken,isuse) VALUES(?,?,?,?,?,?,?,?,?,?,1)';
            var newtoken = publictool.guid();
            var addSqlParams = [phone.account, phone.password, phone.lever, phone.start_timestamp, phone.end_timestamp, phone.company_name, phone.name, phone.tel, phone.qq, newtoken];

            client.query(addSql, addSqlParams, function (err, result) {
                if (err) {
                    console.log('[INSERT ERROR] - ', err.message);
                    publictool.returnErr(res, '插入参数错误', 1);
                    return;
                }

                publictool.returnErr(res, '操作成功', 0);
                client.end();
                return;
            });
        }
    });
}